﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Bling.Core;
using Bling.WPF;
using Bling.WPF.Custom;
using Bling.Util;
using Bling.Shaders;
using Bling.Graphics;
using Bling.WPF3D;

namespace Bling.Tutorial {
  public class Shaders : Canvas {
    public Shaders() {
      CanvasBl canvas = this;
      // The image we wil l use in the example.
      var UseImage = new ImageBl(canvas) { 
        Height = 500,
        Source = new BitmapImage("Resources/Autumn.jpg".MakePackUri(typeof(Shaders))),
        CenterPosition = canvas.CenterSize 
      };
      // do some simple layout.
      Double2Bl At = new Double2Bl(0, 0);
      At = new ButtonBl(canvas) {
        LeftTop = At, Content = "None",
        // no-op pixel effect.
        Click = () => UseImage.Effect.Custom = (input,uv) => input[uv]
      }.RightTop;

      At = new ButtonBl(canvas) {
        LeftTop = At, Content = "FlipH",
        // flip horizontal pixel effect.
        Click = () => UseImage.Effect.Custom = (input,uv) => input[new Double2Bl(1 - uv.X, uv.Y)]
      }.RightTop;

      At = new ButtonBl(canvas) {
        LeftTop = At, Content = "FlipV",
        // flip vertical pixel effect.
        Click = () => UseImage.Effect.Custom = (input, uv) => input[new Double2Bl(uv.X, 1 - uv.Y)]
      }.RightTop;

      At = new ButtonBl(canvas) {
        LeftTop = At,
        Content = "Swirl",
        // a simple swirl.
        Click = () => UseImage.Effect.Custom = (input,uv) => input[uv + (uv - 0.5).ClockwisePerp.Normalize * 0.1],
      }.RightTop;
      // build a thumb for the next shader.
      ThumbBl thumbA = new ThumbBl(canvas) {
        CenterPosition = canvas.CenterSize, ZIndex = 1, CanDrag = true, Background = Brushes.Red,
      };
      // A slider to control light.
      LabelSliderBl slider = new LabelSliderBl(canvas) {
        Minimum = 0, Maximum = 1, Value = 0.5,
        Width = UseImage.Width, LeftBottom = UseImage.LeftTop, LabelName = "Light", Visibility = false,
      };
      // a lense pixel effect.
      At = new ButtonBl(canvas) {
        LeftTop = At, Content = "Lense",
        Click = () => UseImage.Effect.Custom = (input,uv) => {
          slider.Visibility = true;
          slider.LabelName = "light";
          Double2Bl v = ((uv * UseImage.Size) - (thumbA.CenterPosition - UseImage.LeftTop));
          DoubleBl l = (v.Length / 100);
          l = (l <= 1).Condition(l.Pow(1d + slider.Value), l);

          var n = v.Normalize;
          var clr = input[uv + (l * n * .1)];
          var clrB = input[uv - (l * n * .1)];
          var antiAlias = 1d - ((l - 1) / .01).Saturate;

          return (l <= 1).Condition(l.Lerp(clr, Colors.LightGray.Bl()), antiAlias.Lerp(input[uv], Colors.LightGray.Bl()));
        }
      }.RightTop;

          }
  }
}
